package binaryTree;

import java.util.LinkedList;
import java.util.Queue;


//给定一个二叉树，找出其最小深度

//最小深度是从根节点到最近叶子节点的最短路径上的节点数量

public class  MinDepth {
    //层序遍历实现
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            depth++;
            TreeNode cur = null;
            for (int i = 0; i < size; i++) {
                cur = queue.poll();
                //如果当前节点的左右孩子都为空，直接返回最小深度
                if (cur.left == null && cur.right == null){
                    return depth;
                }
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
        }
        return depth;
    }

//    从根节点到叶子节点 使用  前序遍历
//    从叶子结点到根节点 使用  后序遍历

//这道题任然使用前序遍历
    public  int minDepth1(TreeNode  root){
        if (root==null){
            return 0;
        }
        int left= minDepth1(root.left);
        int right= minDepth1(root.right);
        if (root.left==null&&root.right!=null){
            return  1+right;
        }
        if (root.left!=null&&root.right==null){
            return  1+left;
        }
        return 1+Math.min(left,right);
    }

    public static void main(String[] args) {
        TreeNode root= new TreeNode(5);
        TreeNode treeNode1 = new TreeNode(3);
        TreeNode treeNode2=new TreeNode(3);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4= new TreeNode(3);
        root.left=treeNode1;
        root.right=treeNode3;
        treeNode1.left=treeNode2;
        treeNode3.right=treeNode4;
        MinDepth minDepth = new MinDepth();
        System.out.println(minDepth.minDepth1(root));



    }

}
